package com.andrew.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.andrew.entity.Comment;
import com.andrew.entity.CommentForAdmin;
import com.andrew.service.CommentService;
import com.andrew.service.impl.CommentServiceImpl;
import com.google.gson.Gson;

public class GetAllCommentsServlet extends HttpServlet {
	private CommentService commentService=new CommentServiceImpl();
	private Gson gson=new Gson();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置编码
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		try {
			List<Comment> allComments = commentService.getAllComments();
			
			List<CommentForAdmin> allCommentForAdmin=new ArrayList<CommentForAdmin>();
			for (Comment comment:allComments) {
				CommentForAdmin commentForAdmin=new CommentForAdmin();
				commentForAdmin.setBookId(comment.getBook().getBookId());
				commentForAdmin.setBookName(comment.getBook().getBookName());
				commentForAdmin.setCommentDate(comment.getCommentTime());
				commentForAdmin.setCommentId(comment.getCommentId());
				commentForAdmin.setContent(comment.getCommentContent());
				commentForAdmin.setUserName(comment.getCustomer().getUserName());
				allCommentForAdmin.add(commentForAdmin);
			}
			
			String json=gson.toJson(allCommentForAdmin);
			System.out.println(json);
			resp.getWriter().write(json);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}
}
